#!/bin/bash
#
# Functions for working with attribute strings (pipe-separated name=value
# pairs used internally in some Pulley data structures) and arrays of
# attribute strings.
#
# Author:   Dr. Mike Murphy (mmurphy2@coastal.edu)
# Revision: 18 November 2013
#
#   Copyright 2013 Coastal Carolina University
#
#   Licensed under the Apache License, Version 2.0 (the "License");
#   you may not use this file except in compliance with the License.
#   You may obtain a copy of the License at
#
#       http://www.apache.org/licenses/LICENSE-2.0
#
#   Unless required by applicable law or agreed to in writing, software
#   distributed under the License is distributed on an "AS IS" BASIS,
#   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
#   See the License for the specific language governing permissions and
#   limitations under the License.


## extract_element <element name> <attribute string>
##
## Extracts the value of an element named <element name> from
## <attribute string>, where <attribute string> is a string of attributes
## in name=value format, separated by pipe (|) characters. Echoes the value
## and returns 0 on success, returns non-zero if the name cannot be found.
##
function extract_element() {
	local status=1
	local name=
	local value=
	local item=
	local remainder="$2"
	
	item=$(echo "${remainder}" | sed 's/|.*//')
	remainder=$(echo "${remainder}" | sed 's/^.*|//')
	while [[ ${status} -ne 0 && -n "${item}" ]]; do
		name=$(echo "${item}" | sed 's/=.*//')
		value=$(echo "${item}" | sed 's/.*=//')
		
		if [[ "${name}" == "$1" ]]; then
			status=0
			echo "${value}"
		fi
		
		item=$(echo "${remainder}" | 's/|.*//')
		remainder=$(echo "${remainder}" | sed 's/^.*|//')
	done
	
	return ${status}
}


## find_entry <element name> <element value> <attribute string> [ ... ]
##
## Echoes the first attribute string in the set of provided attribute
## strings where the attribute string contains the element <element name>
## with value <element value>. Returns 0 on success, non-zero if no
## matching attribute string is found.
##
function find_entry() {
	local status=1
	local matchname=
	local matchvalue=
	local value=
	
	matchname="$1"
	shift
	matchvalue="$1"
	shift
	
	while [[ $# -gt 0 ]]; do
		value=$(extract_element "${matchname}" "$1")
		if [[ "${value}" == "${matchvalue}" ]]; then
			echo "$1"
			status=0
			break
		fi
		shift
	done
	
	return ${status}
}
